<?
    /* -*- Mode: PHP5; tab-width: 4; indent-tabs-mode: nil; basic-offset: 4 -*- */

    /*********************************************************
    *            --== InArch ==--
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @version n/a
    * @since 04.06.2005
    * @copyright essentialmind.com 2005
    *
    *********************************************************/
    
    /***
    * Class adminUsers
    ****
    * This class represents the users part of a solution
    ****
    * @package adminModules
    * @author A Kulikov <a.kulikov@gmail.com>
    * @version n/a
    * @since 04.06.2005
    * @copyright essentialmind.com 2005
    ***/
    class adminUsers extends adminModule{

        /**
         * Process user inputs
         * 
         * @return void 
         **/
        public function process(){
            //is there a POST submission?
            //new user
            if(isset($_POST['submitNewUser'])){
                $this->addUser();
            }
            
            //new group
            if(isset($_POST['submitNewGroup'])){
                $this->addGroup();
            }
            
            //fetch groups
            $groups = $this->db->getAll("SELECT * FROM user_group ORDER BY id ASC");
            
            //fetch members
            foreach($groups as $key => $val){
                $groups[$key]['members'] = $this->db->getAll("SELECT ua.login, ua.id FROM user_in_group AS ug LEFT JOIN user_access AS ua ON (ug.uid = ua.id) WHERE ug.gid = " . $val['id']);
            }
            
            //give data to smarty
            $this->smarty->assign('adminGroups',$groups);
            $this->smarty->assign('groups',$this->db->getAssoc("SELECT id, name FROM user_group ORDER BY id"));
            
            //unset autoload cookie, if any
            if(isset($_COOKIE['probableUser'])){
                setcookie('probableUser',null,time(),'/');   
            }
        }
        
        
        
        /**
         * Adds a new (admin) user to the current solution
         *
         */
        protected function addUser(){
            //error check input
            $errors = array();
            $login  = trim(htmlspecialchars(strtolower($_POST['login'])));
            $name   = trim(htmlspecialchars($_POST['fullName']));
            $email  = trim(htmlspecialchars(strtolower($_POST['eMail'])));
            $gid    = (int)$_POST['group'];
            
            //valid login?
            if(!eregi("^[A-Za-z0-9_\.\-]{3,}$",$login)){
                $errors['login'] = true;
            }
            
            //login taken?
            if($this->db->getOne("SELECT id FROM user_access WHERE login = '$login'")){
                $errors['loginTaken'] = true;
            }
            
            //full name?
            if(strlen($name) < 2){
                $errors['fullName'] = true;   
            }
            
            //email
            if(!eregi("^[A-Za-z0-9_\.\-]+@[A-Za-z0-9_\.\-]+\.[A-Za-z0-9_\-][A-Za-z0-9_\-]+$", $email)){
                $errors['eMail'] = true;
            }
            
            //are there errors?
            if(empty($errors)){
                //lets try some magic
                try{
                    //log action
                    $this->log->recordAction("Adding a new user -- \"$login\" to group $gid");
                    
                    //generate password
                    $pGen = new passwordGenerator();
                    $passwd = $pGen->getPass(2,0);
                    
                    //start transaction
                    $this->db->StartTrans();
                    
                    //insert user record
                    $this->db->Execute("INSERT INTO user_access(login,passwd) VALUES('$login',md5('$passwd'))");
                    $uid = $this->db->getOne("SELECT last_value FROM user_access_id_seq");
                    
                    //insert group record
                    $this->db->Execute("INSERT INTO user_in_group(gid,uid) VALUES($gid,$uid)");
                    
                    //insert user data record
                    $this->db->Execute("INSERT INTO user_data(uid,fullname,email) VALUES($uid,'$name','$email')");
                    
                    //send e-mail to user
                    $this->smarty->assign(array(
                                            'login'=>$login,
                                            'password'=>$passwd,
                                            'gid'=>$gid
                                          ));
                                          
                    $text       = $this->smarty->preFetch('emails/newuser.txt');
					// $html 		= null;
                    $myMailer   = new mailGateway();
                    $myMailer->send($email,'Access Data / '.$GLOBALS['_CONFIG']['title'],$text,$GLOBALS['_CONFIG']['bot']);
                    
                    //end transaction
                    $this->db->CompleteTrans();
                    
                    //log action
                    $this->log->recordAction("Successfully added user -- \"$login\" to group $gid");
                    
                    //reset POST
                    unset($_POST);
                    
                    //redirect
                    header('Location: '.$GLOBALS['_CONFIG']['admin_root'].$_GET['view']  .'/?confirmNewUser=true');
                    exit;
                            
                }catch(Exception $e){
                    //log error
                    $this->log->recordError($e->getMessage());
                    
                    //redirect browser to tech error page
                    //has to be implemented
                }  
            }else{
                $this->smarty->assign('userErrors',$errors);
            }
        }
        
        
        
        /**
         * Adds a new user group to the current solution
         *
         */
        protected function addGroup(){
            //error check input
            $errors = array();
            $name   = trim(htmlspecialchars(ucfirst($_POST['name'])));
            $admin  = (int)$_POST['admin'];

            //full name?
            if(strlen($name) < 2){
                $errors['name'] = true;   
            }
            
            //are there errors?
            if(empty($errors)){
                //lets try some magic
                try{
                    //log action
                    $this->log->recordAction("Adding a new group -- $name");

                    if($admin == 1){
                        //get internal max ID of admin groups
                        $id = $this->db->getOne("SELECT max(id) + 1 FROM user_group WHERE id < 1000");
                        
                        //insert group record
                        $this->db->Execute("INSERT INTO user_group(id,name) VALUES('$id','$name')");
                    }else{
                        //insert group record
                        $this->db->Execute("INSERT INTO user_group(name) VALUES('$name')");
                    }
                    
                    //reset POST
                    unset($_POST);
                    
                    //log action
                    $this->log->recordAction("Successfully added a new group -- $name");
                    
                    //redirect
                    header('Location: '.$GLOBALS['_CONFIG']['admin_root'].$_GET['view']  .'/?confirmNewGroup=true');
                    exit;
                    
                }catch(Exception $e){
                    //log error
                    $this->log->recordError($e->getMessage());
                    
                    //redirect browser to tech error page
                    //has to be implemented
                }  
            }else{
                $this->smarty->assign('groupErrors',$errors);
            }
        }
        
        
        /**
         * Set action template to controlPanel.html
         * 
         * @return void
         **/
        protected function setTemplate(){
            $this->setActionTemplate('users.html');
        }
    }
?>